package so.shanku.essential.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.*;
import android.view.inputmethod.EditorInfo;
import android.widget.*;
import aym.util.getservicesdata.GetServicesDataQueue;
import aym.util.getservicesdata.GetServicesDataUtil;
import aym.util.json.JsonMap;
import aym.util.json.JsonParseHelper;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import so.shanku.essential.R;
import so.shanku.essential.adapter.MenuAdapter;
import so.shanku.essential.adapter.ShopMallThemeAdapter;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.GetDataQueue;
import so.shanku.essential.getdata.JsonKeys;
import so.shanku.essential.getdata.ShowGetDataError;
import so.shanku.essential.utils.Constant;
import striveen.util.used.view.view.XListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Jaelyn on 2015/9/6 0006.
 * 商城
 */
public class ShopMallFragment extends BaseFragment {

    @ViewInject(R.id.page_lv)
    private XListView xListView;
    @ViewInject(R.id.nodata_layout) //无数据
    private LinearLayout nodataLayout;

    @ViewInject(R.id.main_top_layout) //title
    private LinearLayout main_top_layout;
    @ViewInject(R.id.theme1_layout) //title
    private LinearLayout theme1_layout;
    @ViewInject(R.id.theme2_layout) //title
    private RelativeLayout theme2_layout;
    @ViewInject(R.id.theme1_tv)
    private TextView theme1_tv;
    @ViewInject(R.id.theme2_tv)
    private TextView theme2_tv;
    @ViewInject(R.id.iv_search)
    private ImageView iv_search;


    /**
     * 搜索界面
     */
    @ViewInject(R.id.linearlayout_search)
    private LinearLayout search_layout;
    @ViewInject(R.id.do_search_iv)
    private ImageView do_search_iv;
    @ViewInject(R.id.search_ed)
    private EditText find_search_ed;
    @ViewInject(R.id.tv_search_cancel)
    private TextView cancel_search_tv;

    private int pageSize = 10;
    private int currentPage = 0;
    /**
     * 商品的信息数据
     */
    private List<JsonMap<String, Object>> datas = new ArrayList<JsonMap<String, Object>>();
    private boolean isCallPush = true;
    /**
     * 搜索商品
     */
    private List<JsonMap<String, Object>> searchDatas = new ArrayList<JsonMap<String, Object>>();
    private int searchCurrentPage = 0;
    private boolean isSearchCallPush = true;
    private ShopMallThemeAdapter shopMallThemeAdapter;

    /**
     * 是否为搜索
     */
    private boolean isSearch = false;
    /**
     * 搜索的key
     */
    private String searchKeyStr = "";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.shopping_theme_layout, container, false);
        initCompont(view);
        theme1_tv.setText(R.string.classify);
        theme2_tv.setText(R.string.brand);
        xListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int itemPosition, long id) {
                JsonMap jsonMap_temp;
                if (isSearch) {
                    jsonMap_temp = (JsonMap) searchDatas.get(itemPosition - 1);
                } else {
                    jsonMap_temp = (JsonMap) datas.get(itemPosition - 1);
                }
                String discoreId = jsonMap_temp.getStringNoNull("Id");
                activity.seeShopThemeDetail(discoreId);
            }
        });
        find_search_ed.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    startSearch();
                    return true;
                }
                return false;
            }
        });
        return view;
    }

    private void startSearch() {
        isSearch = true;
        searchKeyStr = find_search_ed.getText().toString().trim();
        if (TextUtils.isEmpty(searchKeyStr)) {
            toast.showToast(R.string.search_key_null);
        } else {
            searchCurrentPage = 0;
            getServerData();
        }
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        shopMallThemeAdapter = new ShopMallThemeAdapter(activity);
        shopMallThemeAdapter.setItemClickListener(goodsPicItemClickListener);
        xListView.setAdapter(shopMallThemeAdapter);
        xListView.setPullRefreshEnable(true);
        xListView.setPullLoadEnable(true);
        xListView.setXListViewListener(loadMoreListener);
        getServerData();
    }

    private XListView.IXListViewListener loadMoreListener = new XListView.IXListViewListener() {
        @Override
        public void onRefresh() {
            if (isSearch) {
                searchCurrentPage = 0;
            } else {
                currentPage = 0;
            }
            getServerData();
        }

        @Override
        public void onLoadMore() {
            getServerData();
        }
    };

    /**
     * 获取服务器端数据
     */
    private void getServerData() {
        loadingToast.show();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);
        if (isSearch) {
            params.put("currentPage", searchCurrentPage + 1);
            params.put("pageSize", pageSize);
            params.put("Title", searchKeyStr);
        } else {
            params.put("currentPage", currentPage + 1);
            params.put("pageSize", pageSize);
            //params.put("Title",searchKeyStr);
        }
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.Action_GetDiscover);

        queue.setParamsNoJson(params);
        queue.setCallBack(callBack);
        queue.setWhat(GetDataConfing.What_GetDiscover);
        getDataUtil.getData(queue);
    }


    private GetServicesDataUtil.IGetServicesDataCallBack callBack = new GetServicesDataUtil.IGetServicesDataCallBack() {

        @Override
        public void onLoaded(GetServicesDataQueue entity) {
            xListView.stopLoadMore();
            xListView.stopRefresh();
            if (entity.isOk()) {
                if (ShowGetDataError.isCodeSuccess(activity, entity.getInfo())) {
                    if (entity.what == GetDataConfing.What_GetDiscover) {
                        List<JsonMap<String, Object>> temp_data = JsonParseHelper.getJsonMap_List_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                        setAdapterData(temp_data);
                        validateData();
                    }
                }
            } else {
                ShowGetDataError.showNetError(activity);
            }
            loadingToast.dismiss();
        }

    };

    /**
     * 校验数据 显示无数据等
     * 是否请求正常 网络错误且数据为空的话显示网络异常界面 提供刷新的接口
     *
     * @param
     */
    private void validateData() {
        if (isSearch) {
            if (searchDatas == null || searchDatas.size() == 0) {
                xListView.setVisibility(View.GONE);
                nodataLayout.setVisibility(View.VISIBLE);
            } else {
                xListView.setVisibility(View.VISIBLE);
                nodataLayout.setVisibility(View.GONE);
            }
        } else {
            if (datas == null || datas.size() == 0) {
                xListView.setVisibility(View.GONE);
                nodataLayout.setVisibility(View.VISIBLE);
            } else {
                xListView.setVisibility(View.VISIBLE);
                nodataLayout.setVisibility(View.GONE);
            }
        }
    }

    private void setAdapterData(List<JsonMap<String, Object>> temp_data) {
        if (temp_data.size() == 0 || temp_data.size() % pageSize != 0) {
            xListView.setPullLoadEnable(false);
            if (isSearch) {
                isSearchCallPush = false;
            } else {
                isCallPush = false;
            }
        } else {
            xListView.setPullLoadEnable(true);
            if (isSearch) {
                isSearchCallPush = true;
            } else {
                isCallPush = true;
            }
        }
        if (isSearch) {
            if (searchCurrentPage == 0) {
                searchDatas = temp_data;

                shopMallThemeAdapter.setDatas(searchDatas);
                //ptr_list.setAdapter(shoppingAdapter);
                xListView.setAdapter(shopMallThemeAdapter);
                shopMallThemeAdapter.notifyDataSetChanged();
            } else {
                searchDatas.addAll(temp_data);
                shopMallThemeAdapter.notifyDataSetChanged();
            }
            searchCurrentPage++;
        } else {
            if (currentPage == 0) {
                datas = temp_data;
                shopMallThemeAdapter.setDatas(datas);
                //ptr_list.setAdapter(shoppingAdapter);
                xListView.setAdapter(shopMallThemeAdapter);
                shopMallThemeAdapter.notifyDataSetChanged();
            } else {
                datas.addAll(temp_data);
                shopMallThemeAdapter.notifyDataSetChanged();
            }
            currentPage++;
        }
    }

    /**
     * item中 控件的点击事件
     */
    private ShopMallThemeAdapter.ItemClickListener goodsPicItemClickListener = new ShopMallThemeAdapter.ItemClickListener() {

        @Override
        public void onItemClickListener(int type, int itemPosition, int childPosition) {

            if (type == Constant.COLLECT_IV_CLICK) {
//				JsonMap jsonMap_temp = (JsonMap) datas.get(itemPosition);
//				JsonMap productInfo_jsonMap = ((JsonMap) jsonMap_temp.getList_JsonMap("ProductList").get(childPosition));//商品信息
//				String goodsId = productInfo_jsonMap.getStringNoNull("ProductId");
                JsonMap jsonMap_temp;
                if (isSearch) {
                    jsonMap_temp = (JsonMap) searchDatas.get(itemPosition);
                } else {
                    jsonMap_temp = (JsonMap) datas.get(itemPosition);
                }

            } else if (type == Constant.SHARE_IV_CLICK) {

            }

        }
    };

    private void initCompont(View view) {
        ViewUtils.inject(this, view);
    }


    private PopupWindow mSourceListPop;
    private ArrayList<JsonMap<String, Object>> sourceData;
    private boolean isOutTouch = false;

    /**
     * 来源
     *
     * @param view
     */
    @OnClick(R.id.theme1_tv)
    public void theme1_tv_click(View view) {
        if (mListPop != null && mListPop.isShowing()) {
            mListPop.dismiss();
        }
        isSortOutTouch = false;
        if (mSourceListPop != null && mSourceListPop.isShowing()) {
            mSourceListPop.dismiss();
            return;
        }
        if (isOutTouch) {
            isOutTouch = false;
            return;
        }
        ListView listView = new ListView(activity);
        listView.setDivider(activity.getResources().getDrawable(R.drawable.hor_line));
        int pad = getResources().getDimensionPixelSize(R.dimen.common_margin);
        listView.setPadding(pad, 0, pad, 0);
        MenuAdapter menuAdapter = new MenuAdapter(activity, sortData);
        listView.setAdapter(menuAdapter);
        //window.setFocusable(true);//如果不设置setFocusable为true，popupwindow里面是获取不到焦点的，那么如果popupwindow里面有输入框等的话就无法输入。
        mSourceListPop = new PopupWindow(listView, MyApplication.getInstance().getScreenWidth() / 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        mSourceListPop.setBackgroundDrawable(getResources().getDrawable(R.drawable.cus_grey_border_frame));
        mSourceListPop.setOutsideTouchable(true);
        mSourceListPop.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    mSourceListPop.dismiss();
                    isOutTouch = true;
                }
                return false;
            }
        });

        mSourceListPop.showAsDropDown(theme1_layout);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                theme2_tv.setText(sortData.get(position).getStringNoNull("title"));
                mSourceListPop.dismiss();
            }
        });
    }


    private PopupWindow mListPop;
    private ArrayList<JsonMap<String, Object>> sortData;
    private boolean isSortOutTouch = false;

    /**
     * 排序
     *
     * @param view
     */
    @OnClick(R.id.theme2_tv)
    public void theme2_tv_click(View view) {
        if (mSourceListPop != null && mSourceListPop.isShowing()) {
            mSourceListPop.dismiss();
        }
        isOutTouch = false;
        if (mListPop != null && mListPop.isShowing()) {
            mListPop.dismiss();
            return;
        }

        if (isSortOutTouch) {
            isSortOutTouch = false;
            return;
        }
        ListView listView = new ListView(activity);
        listView.setDivider(activity.getResources().getDrawable(R.drawable.hor_line));
        int pad = getResources().getDimensionPixelSize(R.dimen.common_margin);
        listView.setPadding(pad, 0, pad, 0);
        MenuAdapter menuAdapter = new MenuAdapter(activity, sortData);
        listView.setAdapter(menuAdapter);
        mListPop = new PopupWindow(listView, MyApplication.getInstance().getScreenWidth() / 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        mListPop.setBackgroundDrawable(getResources().getDrawable(R.drawable.cus_grey_border_frame));
        mListPop.setOutsideTouchable(true);
        mListPop.setSplitTouchEnabled(false);
        mListPop.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    mListPop.dismiss();
                    isSortOutTouch = true;
                }
                return false;
            }
        });
        mListPop.showAsDropDown(theme2_layout);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                theme2_tv.setText(sortData.get(position).getStringNoNull("title"));
                mListPop.dismiss();
            }
        });
    }

    /**
     * 搜索图标
     *
     * @param view
     */
    @OnClick(R.id.iv_search)
    public void iv_search_click(View view) {

        main_top_layout.setVisibility(View.GONE);
        search_layout.setVisibility(View.VISIBLE);
    }

    /**
     * 搜索
     *
     * @param view
     */
    @OnClick(R.id.do_search_iv)
    public void do_search_iv_click(View view) {
        startSearch();
    }


    @OnClick(R.id.tv_search_cancel)
    public void cancel_search_tv_click(View view) {
        if (searchCurrentPage > 0) { //搜索过
            searchCurrentPage = 0;
            searchDatas.clear();
            searchKeyStr = "";

            shopMallThemeAdapter.setDatas(datas);
            //ptr_list.setAdapter(shoppingAdapter);
            xListView.setAdapter(shopMallThemeAdapter);
            shopMallThemeAdapter.notifyDataSetChanged();
            xListView.setPullLoadEnable(isCallPush);
        }
        main_top_layout.setVisibility(View.VISIBLE);
        search_layout.setVisibility(View.GONE);
        isSearch = false;
        validateData();
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (mListPop != null && mListPop.isShowing()) {
            mListPop.dismiss();
        }

        if (mSourceListPop != null && mSourceListPop.isShowing()) {
            mSourceListPop.dismiss();

        }

        isOutTouch = false;
        isSortOutTouch = false;
    }

    /**
     * back 键处理
     * @return   true：消费此次返回  false  不处理
     */
    public boolean backKeyClick(){
        isOutTouch = false;
        isSortOutTouch = false;
        if (mListPop != null && mListPop.isShowing()) {
            mListPop.dismiss();
            return true;
        }

        if (mSourceListPop != null && mSourceListPop.isShowing()) {
            mSourceListPop.dismiss();
            return true;
        }
        return false;
    }
}